package com.x86.util;

import ch.qos.logback.classic.sift.AppenderFactoryUsingJoran;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.x86.domain.Admin;
import com.x86.domain.User;

import java.util.Calendar;

public class JwtUtil {
    private static String sign="$x86$";

    /**
     * 生成token，管理员
     * @param admin
     * @return
     */
    public static String getTokenByAdmin(Admin admin){
        Calendar instance = Calendar.getInstance();
        //3天过期
        instance.add(Calendar.DATE,3);
        String token = JWT.create()
                .withClaim("admin", admin.getUsername())
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(JwtUtil.sign));
        return token;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(JwtUtil.sign)).build().verify(token);
    }
    /**
     * 生成token，user
     * @param user
     * @return
     */
    public static String getTokenByUser(User user){
        Calendar instance = Calendar.getInstance();
        //3天过期
        instance.add(Calendar.DATE,3);
        String token = JWT.create()
                .withClaim("admin", user.getId())
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(JwtUtil.sign));
        return token;
    }

    /**
     * 通过token获取用户的id
     * @param token
     * @return
     */
    public static Integer getUserId(String token){
        DecodedJWT verify = JwtUtil.verify(token);
        Claim admin = verify.getClaim("admin");
        Integer integer = admin.asInt();
        return integer;
    }

}
